import { ipcMain } from 'electron'
import db from '@/main/db'

interface RunResult {
  lastID: number
  changes: number
}

export function setupDbHandlers(): void {
  // 查询单条记录
  ipcMain.handle('db.get', async (_, sql: string, ...params: any[]) => {
    return new Promise((resolve, reject) => {
      db.get(sql, ...params, (err: Error | null, row: any) => {
        if (err) reject(err)
        else resolve(row)
      })
    })
  })

  // 查询多条记录
  ipcMain.handle('db.all', async (_, sql: string, ...params: any[]) => {
    return new Promise((resolve, reject) => {
      db.all(sql, ...params, (err: Error | null, rows: any[]) => {
        if (err) reject(err)
        else resolve(rows)
      })
    })
  })

  // 执行SQL
  ipcMain.handle('db.run', async (_, sql: string, ...params: any[]) => {
    return new Promise((resolve, reject) => {
      db.run(sql, ...params, function(this: RunResult, err: Error | null) {
        if (err) reject(err)
        else resolve({ lastID: this.lastID, changes: this.changes })
      })
    })
  })
}
